from rest_framework.response import Response
from rest_framework import status

from common.enums import BaseCodeEnum


class R(Response):
    """自定义响应"""

    def __init__(self, data=None, status=status.HTTP_200_OK, headers=None):
        super().__init__(data, status, headers=headers)

    @staticmethod
    def make_std_response_data(result_code=0, message="success", data=None):
        """封装返回标准响应数据

        :param result_code: 状态码
        :param message: 响应信息
        :param data: 数据对象
        :return: 标准响应数据
        """
        if not data:
            data = {}
        return {
            "code": result_code,
            "message": message,
            "data": data
        }

    @staticmethod
    def success(data=None, message="success", code=0):
        """响应返回成功消息

        :param data: 数据对象
        :param message: 响应信息
        :param code: 状态码
        :return: Response对象
        """
        ret_data = R.make_std_response_data(code, message, data)
        return R(ret_data)

    @staticmethod
    def error(data=None, message="error", code=400, base_code_enum: BaseCodeEnum = None, status=status.HTTP_200_OK):
        """响应返回错误消息

        :param data: 数据对象
        :param message: 响应信息
        :param code: 状态码
        :param base_code_enum: 状态枚举类（如果传入状态枚举类参数，则优先取状态枚举类内的信息）
        :param status: HTTP响应状态码
        :return: Response对象
        """
        # 如果传入状态枚举类参数，则优先取状态枚举类内的信息
        if base_code_enum is not None:
            message = base_code_enum.desc
            code = base_code_enum.code
        ret_data = R.make_std_response_data(code, message, data)
        return R(ret_data, status)
